/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MovieTrees.Tool;

import MovieTrees.Record.MovieInfo;
import MovieTrees.Record.VideoItem;
import java.io.File;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 *
 *   @author wcss
 */
public class MovieXMLTreeReader {

    public static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    public static void writeXML(ArrayList<MovieInfo> miList, String path) {
        try {
            DocumentBuilder dbr = dbf.newDocumentBuilder();
            org.w3c.dom.Document doc = dbr.newDocument();
            Element first = doc.createElement("tree");            
            Element type = doc.createElement("type");
            Element list = doc.createElement("list");
            ArrayList<String> typeNames = new ArrayList<String>();
            ArrayList<Element> typeObjs = new ArrayList<Element>();            
            for (MovieInfo mi : miList) {
                Element node = doc.createElement("item");

                Element name = doc.createElement("name");
                name.setTextContent(mi.movieName);
                node.appendChild(name);
                Element downtype = doc.createElement("downtype");
                downtype.setTextContent(mi.movieDownloadType);
                node.appendChild(downtype);
                Element playtype = doc.createElement("playtype");
                playtype.setTextContent(mi.moviePlayMode);
                node.appendChild(playtype);
                
                Element image = doc.createElement("image");
                image.setTextContent(mi.movieImage);
                node.appendChild(image);
                
                Element sortNode = doc.createElement("type");
                String sortKey = "";
                Element sorts = doc.createElement("data");                
                for (String s : mi.movieTreePath)
                {
                    sortKey += s + "<<TT>>";
                }
                if (mi.movieTreePath.size()== 1)
                {
                    sorts.setAttribute("A", mi.movieTreePath.get(0));
                }else if (mi.movieTreePath.size() >= 2)
                {
                    sorts.setAttribute("A", mi.movieTreePath.get(0));
                    sorts.setAttribute("B", mi.movieTreePath.get(1));
                }
                if (typeNames.contains(sortKey))
                {
                    //sortNode.setTextContent("" + typeNames.indexOf(sortKey) + 1);   
                }else
                {
                    typeNames.add(sortKey);
                    typeObjs.add(sorts);
                }
                typeNames.trimToSize();
                typeObjs.trimToSize();
                sortNode.setTextContent((typeNames.indexOf(sortKey) + 1) + "");
                
                node.appendChild(sortNode);

                Element readmeNode = doc.createElement("readme");
                readmeNode.setTextContent(mi.movieInfo);
                node.appendChild(readmeNode);

                for (VideoItem vi : mi.subItems) {
                    Element videoNode = doc.createElement("video");
                    videoNode.setAttribute("name", vi.videoName);
                    videoNode.setAttribute("url", vi.videoUrl);
                    node.appendChild(videoNode);
                }

                list.appendChild(node);
            }
            
            int indexx = 0;
            for(Element ele : typeObjs)
            {
                indexx++;
                ele.setAttribute("id", indexx+"");
                type.appendChild(ele);
            }
            first.appendChild(type);
            first.appendChild(list); 
            doc.appendChild(first);
            
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new java.io.File(path));
            transformer.transform(source, result);

        } catch (Exception ex) {
            Logger.getLogger(MovieXMLTreeReader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static ArrayList<MovieInfo> readXML(String path) 
    {
        ArrayList<MovieInfo> list = new ArrayList<MovieInfo>();
        Hashtable<String,Element> types = new Hashtable<String,Element>();
        File ff = new File(path);
        if (ff.exists())
        {
            try {
                DocumentBuilder dbr = dbf.newDocumentBuilder();
                org.w3c.dom.Document doc = dbr.parse(ff);
                Element first = doc.getDocumentElement();
                NodeList typeList = ((Element)first.getElementsByTagName("type").item(0)).getElementsByTagName("data");                
                for(int f = 0;f < typeList.getLength();f++)
                {
                    types.put(((Element)typeList.item(f)).getAttribute("id"),((Element)typeList.item(f)));    
                }
                
                NodeList alllist = first.getElementsByTagName("list");
                NodeList movieList = ((Element)alllist.item(0)).getElementsByTagName("item");
                for(int h=0;h < movieList.getLength();h++)
                {
                    Element item = (Element)movieList.item(h);
                    MovieInfo mii = new MovieInfo();
                    mii.movieName = item.getElementsByTagName("name").item(0).getTextContent();
                    mii.movieID = mii.movieName;
                    mii.movieImage = item.getElementsByTagName("image").item(0).getTextContent();
                    mii.movieDownloadType = item.getElementsByTagName("downtype").item(0).getTextContent();
                    mii.moviePlayMode = item.getElementsByTagName("playtype").item(0).getTextContent();
                    mii.movieInfo = item.getElementsByTagName("readme").item(0).getTextContent();
                    String typeId = item.getElementsByTagName("type").item(0).getTextContent();
                    Element typeNode = types.get(typeId);
                    if (typeNode.hasAttribute("A") && typeNode.hasAttribute("B"))
                    {
                        mii.movieTreePath.add(typeNode.getAttribute("A"));
                        mii.movieTreePath.add(typeNode.getAttribute("B"));
                        
                    }else
                    {
                        mii.movieTreePath.add(typeNode.getAttribute("A"));
                    }
                    NodeList videoList = item.getElementsByTagName("video");
                    for(int u = 0; u < videoList.getLength();u++)
                    {
                        Element videoNode = ((Element)videoList.item(u));
                        VideoItem vi = new VideoItem();
                        vi.videoName = videoNode.getAttribute("name");
                        vi.videoUrl = videoNode.getAttribute("url");
                        vi.videoDownloadType = mii.movieDownloadType;
                        vi.videoPlayMode = mii.moviePlayMode;
                        mii.subItems.add(vi);
                    }
                    list.add(mii);                    
                }
            } catch (Exception ex) {
                Logger.getLogger(MovieXMLTreeReader.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
        return list;
    }
}
